package me.shurufa.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.van.fanyu.library.Compresser;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.activities.AccountActivity;
import me.shurufa.activities.BaseInfoActivity;
import me.shurufa.activities.ChatMessageActivity;
import me.shurufa.activities.PhotoPickerActivity;
import me.shurufa.activities.SettingsActivity;
import me.shurufa.model.LoginResponse;
import me.shurufa.model.UploadResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Settings;
import me.shurufa.utils.Utils;
import me.shurufa.widget.CircleImageView;
import me.shurufa.widget.crop.Crop;
import me.shurufa.widget.crop.util.FileUtils;

/**
 * "我的"界面
 *NOTICE: 消息Layout上有个红点 用来显示是否有未读消息
 * @FileName: me.shurufa.activities.ProfileFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-18 10:53
 */
public class ProfileFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.user_avatar)
    CircleImageView userAvatar;
    @Bind(R.id.user_nick)
    TextView userNick;
    @Bind(R.id.user_desc)
    TextView userDesc;
    @Bind(R.id.user_account_layout)
    LinearLayout userAccountLayout;
    @Bind(R.id.user_baseinfo_layout)
    LinearLayout userBaseinfoLayout;
    @Bind(R.id.user_message_layout)
    LinearLayout userMessageLayout;
    @Bind(R.id.user_setting_layout)
    LinearLayout userSettingLayout;

    private Dialog dialog;
    private File mTempDir;
    private KProgressHUD kProgressHUD;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if(mTempDir.exists()){
            FileUtils.deleteFile(mTempDir);
        }
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //创建临时文件夹
        mTempDir = new File( Environment.getExternalStorageDirectory(),"shurufa_temp");
        if(!mTempDir.exists()){
            mTempDir.mkdirs();
        }
        //第一次设置UI
        refresh();
        userAvatar.setOnClickListener(this);
        userAccountLayout.setOnClickListener(this);
        userBaseinfoLayout.setOnClickListener(this);
//        userMessageLayout.setOnClickListener(this);
        userMessageLayout.setVisibility(View.GONE);
        userSettingLayout.setOnClickListener(this);
        syncUserInfo();
    }

    private void syncUserInfo() {
        new RequestServerTask<LoginResponse>(LoginResponse.class){

            @Override
            protected String requestServer() {
                Map<String,Object> params = new HashMap<>();
                params.put("token",Global.currentUser.token);
                params.put("withExcerptTotal",1);
                return HttpUtil.post(API.USER_PROFILE,params);
            }

            @Override
            protected void onSuccess(LoginResponse result) {
                if (result.success){
                    String token = Global.currentUser.token;
                    Global.currentUser = result.data;
                    Global.currentUser.token = token;
                    //覆盖Sp
                    Settings.delUser(String.valueOf(Global.currentUser.uid));
                    Settings.saveUser(Global.currentUser);
                    refresh();
                }
            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.user_account_layout:
                intent = new Intent(getActivity(),AccountActivity.class);
                startActivity(intent);
                break;
            case R.id.user_baseinfo_layout:
                intent = new Intent(getActivity(), BaseInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.user_message_layout:
                intent = new Intent(getActivity(), ChatMessageActivity.class);
                startActivity(intent);
                break;
            case R.id.user_setting_layout:
                intent = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.user_avatar:
//                intent = new Intent(getActivity(), ModifyAvatarActivity.class);
//                startActivity(intent);
                showDialog();
                break;
            case R.id.take_photo:
                dialog.dismiss();
                showCamera();
                break;
            case R.id.take_gally:
                dialog.dismiss();
                intent = new Intent(getActivity(),PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            case R.id.cancel:
                dialog.dismiss();
                break;
        }
    }

    /** 拍照时存储拍照结果的临时文件 */
    public final static int REQUEST_CAMERA = 1;
    private static final int PICK_PHOTO = 2;
    private String mCurrentPhotoPath;

    /**
     * 选择相机
     */
    private void showCamera() {
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(cameraIntent.resolveActivity(getActivity().getPackageManager()) != null){
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            String fileName = "Temp_camera" + String.valueOf( System.currentTimeMillis())+".png";
            File mTmpFile = new File(mTempDir,fileName);
            Uri uri = Uri.fromFile(mTmpFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            mCurrentPhotoPath = uri.getPath();
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        }else{
            Utils.showToast(R.string.msg_no_camera);
        }
    }

    //dialog choose 回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 相机拍照完成后，返回图片路径 打开剪裁页面
        if(requestCode == REQUEST_CAMERA){
            if(resultCode == Activity.RESULT_OK) {
                if (!TextUtils.isEmpty(mCurrentPhotoPath)){
                    beginCrop(Uri.fromFile( new File( mCurrentPhotoPath)));
                }
            }
        }else
        //相册选择完成后，返回图片路径 打开剪裁页面
        if(requestCode == PICK_PHOTO){
            if(resultCode == Activity.RESULT_OK){
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                if (result!=null&&result.size()>0){
                   beginCrop(Uri.fromFile(new File(result.get(0))));
                }
            }
        }else
        //处理剪裁图片的回调
        if (requestCode == Crop.REQUEST_CROP){
            LogUtils.kLog().e("REQUEST_CROP");
            if (resultCode == Activity.RESULT_OK){
                LogUtils.kLog().e("RESULT_OK");
                Compresser compresser = new Compresser(75,(Crop.getOutput(data)).getPath());
                compresser.doCompress(new Compresser.CompleteListener() {
                    @Override
                    public void onSuccess(String s) {
                        LogUtils.kLog().e("new Path:"+s);
                        uploadImg(s);
                    }
                });

            }
        }
    }
    File tempFile;
    private void uploadImg(String path) {
        File file = new File(path);
        kProgressHUD = KProgressHUD.create(getActivity());
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(getString(R.string.commit_pls_wait))
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
        /*OkHttpUtils.post()//
                .addFile("image",file.getName(),file)//
                .url(API.USER_UPLOAD_IMAGE)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void inProgress(float progress) {}
                    @Override
                    public void onError(Request request, Exception e) {
                        Utils.showToast("提交失败0");
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }
                    }
                    @Override
                    public void onResponse(String s) {
                        doResult(s);
                    }
                });*/
    }

    private void doResult(String s) {
        if (!TextUtils.isEmpty(s)) {
            LogUtils.kLog().d(s);
        }
        UploadResponse result = null;
        try{
            if (!TextUtils.isEmpty(s)){
                result = Global.getGson().fromJson(s,UploadResponse.class);
            }else {
                result = null;
            }
            if (result != null && result.result==1) {
                final String url = result.url;
                if (!TextUtils.isEmpty(url)) {
                    new RequestServerTask<BaseResponse>(BaseResponse.class) {

                        @Override
                        protected String requestServer() {
                            Map<String, Object> param = new HashMap<String, Object>();
                            param.put("token", Global.currentUser.token);
                            param.put("avatar",url);
                            return HttpUtil.post(API.USER_MODIFY_AVATAR,param);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {
                            Global.currentUser.avatar = url;
                            Settings.delUser(String.valueOf(Global.currentUser.uid));
                            Settings.saveUser(Global.currentUser);
                            refresh();
                        }
                    }.start();
                }else
                    Utils.showToast("提交失败2");
            } else {
                if (result!=null&&result.result==0){
                    Utils.showToast(result.msg);
                }else {
                    Utils.showToast("提交失败1");
                }
            }
        }catch (Exception e){}
        finally {
            if (kProgressHUD!=null){
                kProgressHUD.dismiss();
            }
        }
    }




    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis())+".png";
        File cropFile = new File( mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(true).start(getActivity(),this);
    }

    private void showDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_choose_photo, null);
        Button takePhoto = (Button)view.findViewById(R.id.take_photo);
        Button takeGally = (Button) view.findViewById(R.id.take_gally);
        Button cancel = (Button)view.findViewById(R.id.cancel);

        takePhoto.setOnClickListener(this);
        takeGally.setOnClickListener(this);
        cancel.setOnClickListener(this);

        dialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_FRAGMENT_REFRESH)){
            refresh();
        }
    }

    @Override
    public void refresh() {
        super.refresh();
        if (!TextUtils.isEmpty(Global.currentUser.avatar)){
            Glide.with(this).load(Global.currentUser.avatar).into(userAvatar);
        }else {
            //TODO 设置默认头像
            userAvatar.setImageResource(R.drawable.default_avatar);
        }
        if (!TextUtils.isEmpty(Global.currentUser.username));
        userNick.setText(Global.currentUser.username);
        if (!TextUtils.isEmpty(Global.currentUser.description));
        userDesc.setText(Global.currentUser.description);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
